//
//  Company_DetailViewController2.m
//  HuaRun2
//
//  Created by admin on 2017/9/9.
//  Copyright © 2017年 Sunny. All rights reserved.
//

#import "Company_DetailViewController2.h"
#import "Company_DetailHeaderView2.h"
#import "BaseInfoCell.h"
#import "AddressTableViewCell.h"
#import "CustomerTableViewController.h"
#import "Com_DetailModel.h"
#import "NoteTableViewController.h"
#import "Company_DetailPersonListViewController.h"
#import "ContactPersonModel.h"
#import "GiftModel.h"
#import "Com_MeetingModel.h"
#import "AddressModel.h"
#import "Home_Search_NoteCell.h"
#import "ImageLabView.h"

@interface Company_DetailViewController2 ()
@property(nonatomic, strong)Com_DetailModel * detailModel;

@end

@implementation Company_DetailViewController2

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.navigationItem.title = NSLocalizedString(@"公司详情",nil);
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = backItem;

    [self.tableView registerClass:[UITableViewCell class]
           forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:[BaseInfoCell class]
       forCellReuseIdentifier:@"BaseInfoCell"];
    [self.tableView registerClass:[AddressTableViewCell class]
       forCellReuseIdentifier:@"AddressTableViewCell"];
    [self.tableView registerClass:[Home_Search_NoteCell class]
           forCellReuseIdentifier:@"Home_Search_NoteCell"];

    self.tableView.backgroundColor = RGBA(249, 249, 249, 1);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    Company_DetailHeaderView2 * headerView = [Company_DetailHeaderView2 new];
    headerView.frame = CGRectMake(0, 0, kMainScreenWidth, 145);
    self.tableView.tableHeaderView = headerView;

    weakself(ws);
    [headerView.noteView clickViewBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [ws seeNote];
    }];
    
    [headerView.roleView clickViewBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [ws seeContact];
    }];
    [headerView.meetingView clickViewBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [ws seeMeeting];
    }];
    [headerView.giftView clickViewBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [ws seeGift];
    }];

    [self methodBind];
}
- (void)methodBind {
    
    [self fetchCompanyDetail];
    
    [self fetchContactPersonNum];
    [self fetchContactGifNum];
    [self fetchContactMeetingNum];
    
    [self fetchContactAddressList];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - method
//查看地址详情
- (void)seeAddressDetail:(AddressModel *)addressModel{
    
    CustomerTableViewController * customer = [CustomerTableViewController new];
    customer.listType = ListTypeAddress;
    customer.name = _detailModel.name;
    customer.companyName = _detailModel.companyNameChineseC;
    customer.addressModel = addressModel;
    [self.navigationController pushViewController:customer animated:YES];
}

//查看备注
- (void)seeNote {
    NoteTableViewController * customer = [NoteTableViewController new];
    customer.parentId = _detailModel.id ? _detailModel.id : @"";
    customer.noteType = NoteTypeCompany;
    customer.name = _detailModel.name;
    customer.companyName = _detailModel.companyNameChineseC;
    
    [self.navigationController pushViewController:customer animated:YES];
}

//查看联系人
- (void)seeContact {
    if (_contactPersonsArray.count ==0) {
        [self showAlert:NSLocalizedString(@"暂无数据", nil)];
        return;
    }
    Company_DetailPersonListViewController * customer = [Company_DetailPersonListViewController new];
    customer.dataArray = _contactPersonsArray;
    customer.name = _detailModel.name;
    customer.companyName = _detailModel.companyNameChineseC;
    customer.personListType = PersonListTypeCompanyDet;
    [self.navigationController pushViewController:customer animated:YES];
}

//查看会议
- (void)seeMeeting {
    if (_meetingsArray.count ==0) {
        [self showAlert:NSLocalizedString(@"暂无数据", nil)];
        return;
    }

    CustomerTableViewController * customer = [CustomerTableViewController new];
    customer.listType = ListTypeMeetiong;
    customer.dataArray = _meetingsArray;
    customer.name = _detailModel.name;
    customer.companyName = _detailModel.companyNameChineseC;
    [self.navigationController pushViewController:customer animated:YES];
}

//查看礼物
- (void)seeGift {
    if (_giftsArray.count ==0) {
        [self showAlert:NSLocalizedString(@"暂无数据", nil)];
        return;
    }

    CustomerTableViewController * customer = [CustomerTableViewController new];
    customer.listType = ListTypeGift;
    customer.name = _detailModel.name;
    customer.companyName = _detailModel.companyNameChineseC;
    customer.dataArray = _giftsArray;
    customer.navigationItem.title = NSLocalizedString(@"company_detail_gift", nil);
    [self.navigationController pushViewController:customer animated:YES];
}

//重新设置会议名称
- (void)reConfigureHeaderViewName {
    Company_DetailHeaderView2 * headerView = (Company_DetailHeaderView2 * ) self.tableView.tableHeaderView;
    headerView.nameLab.text = [NSString showSpaceStringWithStr: _detailModel.name];
    headerView.companyLab.text = [NSString showSpaceStringWithStr:_detailModel.companyNameChineseC];
    NSLog(@"crc flag %@", _detailModel.crcGroup);
    headerView.crcFlagView.selected = [_detailModel.crcGroup intValue] == 1;
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (void)operateBaseInfoMethod:(BaseInfoCell *)cell {
    //电话
//    @property (nonatomic, strong) ImageLabView * noteView;
//    //打印
//    @property (nonatomic, strong) ImageLabView * contactView;
//    //传真
//    @property (nonatomic, strong) ImageLabView * meetingView;
//    //网址
//    @property (nonatomic, strong) ImageLabView * giftView;

    weakself(ws);
    cell.noteView.clickBlock = ^(EventType type,NSString * text) {
        [ws clickMethodWithType:type text:text];
    };

    cell.contactView.clickBlock = ^(EventType type,NSString * text) {
        [ws clickMethodWithType:type text:text];
    };
    
    cell.meetingView.clickBlock = ^(EventType type,NSString * text) {
        [ws clickMethodWithType:type text:text];
    };
    
    cell.giftView.clickBlock = ^(EventType type,NSString * text) {
        [ws clickMethodWithType:type text:text];
    };
}

- (void)clickMethodWithType:(EventType)type text:(NSString *)text {

    if (type == EventTypeCopy) {
        [self copyTextToPasteboardWithText:text ];
    
    }else if (type == EventTypeCall) {
        
        [self callMethodWithNumber:text];
    }else if (type == EventTypeUrl) {
        
        [self openWebWithUrl:text];
    }else if (type == EventTypeEmail) {
    
        [ToolHelper openEamilWithEmailStr:text];
    }
}

- (void)callMethodWithNumber:(NSString *)number {
    [ToolHelper callWithPhoneNum:number];
}

- (void)copyTextToPasteboardWithText:(NSString *)text {

    BOOL isCanCopy = [ToolHelper copyWithText:text];
    if (isCanCopy) {
        
        [self showAlert:NSLocalizedString(@"copy_success", nil)];
    }
}

- (void)openWebWithUrl:(NSString *)urlStr {
    [ToolHelper openWebWithUrlStr:urlStr];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        BaseInfoCell * cell = [tableView dequeueReusableCellWithIdentifier:@"BaseInfoCell" forIndexPath:indexPath];
        cell.detailModel = _detailModel;
        [self operateBaseInfoMethod: cell];
        return cell;
    }
    
    if (_addressArray.count == 0) {
        Home_Search_NoteCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Home_Search_NoteCell"
                                                                      forIndexPath:indexPath];
        cell.valueLab1.text = NSLocalizedString(@"暂无数据", nil);
        return cell;
        
    }
    weakself(ws);
    AddressTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"AddressTableViewCell" forIndexPath:indexPath];
    cell.addressArray = self.addressArray;
    
    cell.clickBlock = ^(NSInteger index) {
        AddressModel * addressModel = ws.addressArray[index];
        [ws seeAddressDetail:addressModel];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 30 * 5 + 10;
    }
    
    if (_addressArray.count == 0) {
        return 44;
    }
    return 164;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * view = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, kMainScreenWidth, 50))];
    view.backgroundColor = RGBA(249, 249, 249, 1);
    
    UILabel * label = [[UILabel alloc] init];
    label.frame = CGRectMake(10, 10, 150, 20);
    label.font = kFontSize15;
    if (section == 0) {
        label.text = NSLocalizedString(@"基本信息", nil);
    }else if (section == 1) {
        NSString * numberStr = _addressArray.count > 0 ?
        [NSString stringWithFormat:@"(%ld)", self.addressArray.count] : @"";
        
        label.text = [NSString stringWithFormat:@"%@%@",
                      NSLocalizedString(@"公司地址", nil),
                      numberStr];
    }
    label.textColor = [UIColor colorWithHex:@"3c3c3c"];
    [view addSubview:label];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

#pragma mark -- network

//获取公司详情
- (void)fetchCompanyDetail {
    
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kCompanyDetailUrl];
    
    NSString * accountId = _accountId ? _accountId : @"";
    NSDictionary * dic = @{@"accountId": accountId};
    
    weakself(ws);
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];
            return;
        }
        
        Com_DetailModel * detailModel = [Com_DetailModel yy_modelWithJSON:object[@"obj"]];
        ws.detailModel = detailModel;
        
        [ws reConfigureHeaderViewName];
        [ws.tableView reloadData];
        
    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
    }];
}

//获取联系人个数
- (void)fetchContactPersonNum {
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kCompanyDetailListByAccountUrl];
    NSString * accountId = _accountId ? _accountId : @"";
    NSDictionary * dic = @{@"accountId": accountId};
    
    weakself(ws);
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];
            return;
        }

        NSArray * addressArray = [NSArray yy_modelArrayWithClass:[ContactPersonModel class]
                                                            json:object[@"list"]];
        ws.contactPersonsArray = addressArray;
//        if (addressArray.count > 0) {
            Company_DetailHeaderView2 * header = (Company_DetailHeaderView2 * ) ws.tableView.tableHeaderView;
            [header resetContactNum:[NSString stringWithFormat:@"%ld", [object[@"list"] count]]];
//        }
        
    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
    }];
    
}

//获取礼物个数
- (void)fetchContactGifNum {
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kCompanyDetailGiftUrl];
    NSString * accountId = _accountId ? _accountId : @"";
    NSDictionary * dic = @{@"accountId": accountId};
    
    weakself(ws);
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];
            return;
        }
        
        NSArray * addressArray = [NSArray yy_modelArrayWithClass:[GiftModel class]
                                                            json:object[@"list"]];
        ws.giftsArray = addressArray;

//        if (addressArray.count > 0) {
            Company_DetailHeaderView2 * header = (Company_DetailHeaderView2 * ) ws.tableView.tableHeaderView;
            [header resetGiftNum:[NSString stringWithFormat:@"%ld", [object[@"list"] count]]];
//        }

        
    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
    }];
    
}

//获取会议个数
- (void)fetchContactMeetingNum {
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kCompanyDetailMeetingListUrl];
    NSString * accountId = _accountId ? _accountId : @"";
    NSDictionary * dic = @{@"accountId": accountId};
    
    weakself(ws);
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];
            return;
        }
        NSArray * addressArray = [NSArray yy_modelArrayWithClass:[Com_MeetingModel class]
                                                            json:object[@"list"]];
        ws.meetingsArray = addressArray;
        
//        if (addressArray.count > 0) {
            Company_DetailHeaderView2 * header = (Company_DetailHeaderView2 * ) ws.tableView.tableHeaderView;
            [header resetMeetingNum:[NSString stringWithFormat:@"%ld", [object[@"list"] count]]];
            
//        }

        
    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
    }];
    
}


//获取联系人地址
- (void)fetchContactAddressList {
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kCompanyDetailAddressListUrl];
    NSString * accountId = _accountId ? _accountId : @"";
    NSDictionary * dic = @{@"accountId": accountId,
                           @"isPrivate ": @(0)};
    
    weakself(ws);
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];
            return;
        }
        NSArray * addressArray = [NSArray yy_modelArrayWithClass:[AddressModel class]
                                                            json:object[@"list"]];
        if (addressArray.count == 1) {
            AddressModel * model = addressArray[0];
            model.isShowArrow = YES;
        }
        ws.addressArray = addressArray;
        [ws.tableView reloadData];
        
    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
    }];
    
}

@end
